package com.inwavetech.os.util;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.inwavetech.os.BaseOsCheckActivity;
import com.inwavetech.os.OsDetailActivity;
import com.inwavetech.os.R;
import com.inwavetech.os.entity.Os;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by jgskin on 2/9/14.
 */
public class OsWidgetPlotter {
    private final BaseOsCheckActivity context;
    private final ViewGroup container;
    private final SimpleDateFormat dateFormatter;
    private List<Integer> plottedOses;

    public OsWidgetPlotter(BaseOsCheckActivity context, DaoHelper daoHelper, ViewGroup container) {
        this.context = context;
        this.container = container;

        this.plottedOses = new ArrayList<Integer>();
        this.dateFormatter = new SimpleDateFormat("d/M/yy");
    }

    public void plotOses(Collection<Os> oses) {
        // show the oses
        for (Os os: oses) {
            plotOs(os);
        }

        // handle the feedback text
        TextView feedbackText = (TextView) container.findViewById(R.id.main_feedback_text);

        if (feedbackText != null) {
            if (oses.size() > 0) {
                container.removeView(feedbackText);
            } else {
                feedbackText.setText(context.getString(R.string.no_oses));
            }
        }
    }

    public void plotOs(final Os os) {
        if (!plottedOses.contains(os.id)) {
            LinearLayout osWidget = (LinearLayout) context.getLayoutInflater()
                    .inflate(R.layout.view_os_widget, container, false);

            TextView osIdText = (TextView) osWidget.findViewById(R.id.text_os_id);
            TextView clientText = (TextView) osWidget.findViewById(R.id.text_client);
            TextView storeText = (TextView) osWidget.findViewById(R.id.text_store);
            TextView dateText = (TextView) osWidget.findViewById(R.id.text_date);
            TextView statusText = (TextView) osWidget.findViewById(R.id.text_status);

            osIdText.setText(os.original_id);
            clientText.setText(os.client);
            storeText.setText(os.store);
            dateText.setText(dateFormatter.format(os.created_at));
            statusText.setText(context.getString(os.getStatusResource()));

            osWidget.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    context.startActivity(context.buildOsDetailIntent(os.id));
                }
            });

            container.addView(osWidget);

            plottedOses.add(os.id);
        }
    }

    public void clear() {
        container.removeAllViews();
        plottedOses.clear();
    }
}
